package com.wzxl.config.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @author rxbyes
 * @version V1.0
 * @package com.wzxl.config.context
 * @description: TODO (以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.)
 * @date 2017-11-下午3:44
 */

@Service
@Lazy(value = false)
public class SpringContextHolder extends WebApplicationContextUtils implements ApplicationContextAware, DisposableBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpringContextHolder.class);

    public static ApplicationContext applicationContext = null;

    /**
     * 获取ApplicationContext 对象
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void destroy() {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("清除 applicationContext ：{} ", applicationContext);
        }
        SpringContextHolder.applicationContext = null;
    }

    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 实现 Aware 接口，注入到 Context静态变量中
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }
}
